//
//  ViewControllerForKVO.m
//  KVO
//
//  Created by 李广帅 on 16/11/28.
//  Copyright © 2016年 刘桂林. All rights reserved.
//

#import "ViewControllerForKVO.h"

//数据存储模型
#import "modelForKVO.h"
//视图
#import "ViewForKVO.h"

@interface ViewControllerForKVO ()
//模拟请求数据
@property (nonatomic,strong) UIButton *button;
//视图
@property (nonatomic,strong) ViewForKVO *viewUI;

@property (nonatomic,strong) modelForKVO *m1;
@end

@implementation ViewControllerForKVO

- (instancetype)init
{
    self = [super init];
    if (self) {
        //创建UI
        [self viewUI];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //模拟请求数据
    [self createButton];
    
    //注册KOV
    [self registered];
}
#pragma mark -懒加载创建UI视图-
- (ViewForKVO *)viewUI
{
    if (!_viewUI)
    {
        ViewForKVO *view = [[ViewForKVO alloc]init];
        view.frame = CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height-100);
        [self.view addSubview:view];
        view.backgroundColor = [UIColor orangeColor];
        _viewUI = view;
        return _viewUI;
    }
    return _viewUI;
}

#pragma mark -模拟请求数据-
- (void)createButton
{
    _button = [UIButton buttonWithType:UIButtonTypeSystem];
    _button.frame = CGRectMake(0, 0, self.view.frame.size.width, 50);
    _button.backgroundColor = [UIColor redColor];
    [_button setTitle:@"change" forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(change:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];
}
#pragma mark -模拟请求数据-
- (void)change:(UIButton *)button
{
    NSString *name = [NSString stringWithFormat:@"%d",arc4random() % 1000000];
    NSDictionary *dic = @{@"name":name};
    NSLog(@"%@",dic);
    //将拿到的数据存储到数据模型中
    [modelForKVO methodModelForKVO:dic];
}
#pragma mark -注册KOV-
- (void)registered
{
    //一，设立被观察者（被监听者）   //添加一个观察者对象  //KVO通过kvc触发
    _m1 = [modelForKVO sharedManager];
    //参数1：自定义对象
    //参数3：自定义对象的属性
    //参数4：NSKeyValueObservingOptionNew = 0x01,
    //      NSKeyValueObservingOptionOld = 0x02,
    [_m1 addObserver:self
         forKeyPath:@"name"
            options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
            context:nil];
}
//三，一旦监听者的属性值被KVC改变，系统就会触发kvo的回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    //参数一：keyPath 监听对象的属性
    if ([keyPath isEqualToString:@"name"]) {
        //参数二：object代表监听的对象
        modelForKVO *m2 = (modelForKVO *)object;
        
        NSLog(@"name:%@",m2.name);
        
        self.viewUI.label.text = m2.name;
    }
    //参数三：change 新值和旧值
    NSLog(@"change == %@",change);
}
//四，//移除观察者
- (void)dealloc
{
    [_m1 removeObserver:self forKeyPath:@"name"];
}

@end
